package com.muyu.danmo.service.impl;


import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.mapper.DanmoCollectMaterialMapper;
import com.muyu.danmo.mapper.DanmoCollectShellfishMapper;
import com.muyu.danmo.mapper.DanmoInformationCopy1Mapper;
import com.muyu.danmo.mapper.DanmoPortfolioMapper;
import com.muyu.danmo.service.IDanmoCollectShellfishService;
import com.muyu.remote.DanmoMarketProductsAdd;
import com.muyu.system.domain.DanmoMarketPicture;
import com.muyu.system.domain.DanmoMarketProducts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拾贝信息Service业务层处理
 *
 * @author yangle
 * @date 2024-10-30
 */
@Service
public class DanmoCollectShellfishServiceImpl implements IDanmoCollectShellfishService {
    @Autowired
    private DanmoCollectShellfishMapper danmoCollectShellfishMapper;

    /**
     * 查询拾贝信息
     *
     * @param id 拾贝信息主键
     * @return 拾贝信息
     */
    @Override
    public Result selectDanmoCollectShellfishById(Long id) {
        try{
            DanmoCollectShellfish danmoCollectShellfish1 = danmoCollectShellfishMapper.selectDanmoCollectShellfishById(id);
            if (danmoCollectShellfish1 == null){
                return Result.error("暂无作品");
            }
            DanmoCollectShellfish danmoCollectShellfish = new DanmoCollectShellfish();
            danmoCollectShellfish.setViews(danmoCollectShellfish1.getViews() + 1);
            danmoCollectShellfish.setId(id);
            DanmoCollectFootprint danmoCollectFootprint = new DanmoCollectFootprint();
            danmoCollectFootprint.setShellfishId(danmoCollectShellfish.getId());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            danmoCollectFootprint.setUserId(loginUser.getUserid());
            danmoCollectFootprintServiceImpl.insertDanmoCollectFootprint(danmoCollectFootprint);
            danmoCollectShellfishMapper.updateDanmoCollectShellfish(danmoCollectShellfish);
            return Result.success(danmoCollectShellfish1);
        }catch (Exception e){
            return Result.reportedanerror("服务器错误");
        }


    }

    @Autowired
    private DanmoCollectFootprintServiceImpl danmoCollectFootprintServiceImpl;
    /**
     * 查询拾贝信息列表
     *
     * @param danmoCollectShellfish 拾贝信息
     * @return 拾贝信息
     */
    @Override
    public List<DanmoCollectShellfish> selectDanmoCollectShellfishList(DanmoCollectShellfish danmoCollectShellfish) {
        return danmoCollectShellfishMapper.selectDanmoCollectShellfishList(danmoCollectShellfish);
    }


    @Autowired
    private DanmoCollectMemberServiceImpl danmoCollectMemberService;

    @Autowired
    private DanmoInformationCopy1Mapper danmoInformationCopy1Mapper;

    @Autowired
    private DanmoMarketProductsAdd danmoMarketProductsAdd;

    /**
     * 新增拾贝信息
     *
     * @param danmoCollectShellfish 拾贝信息
     * @return 结果
     */
    @Transactional
    @Override
    public Result insertDanmoCollectShellfish(DanmoCollectShellfish danmoCollectShellfish) {


            Result judgment = judgment(danmoCollectShellfish);
            if (judgment!=null){
                return judgment;
            }


            LoginUser loginUser = SecurityUtils.getLoginUser();
//
//            boolean b = danmoCollectMemberService.selectIsShow(loginUser.getUserid());
//            if (b==false){
//                return Result.error("请先开通");
//            }



//            DanmoInformation danmoInformation = danmoInformationServicel.selectUserID(loginUser.getUserid());
//              if (danmoInformation==null){
//                  return Result.error("请先完善个人信息");
//              }
//            danmoCollectShellfish.setAuthor(danmoInformation.getName());
//            danmoCollectShellfish.setUserId(loginUser.getUserid());
////            danmoCollectShellfish.setWidth(();
//            danmoCollectShellfish.setInformationId(danmoInformation.getId());
            DanmoInformationCopy1 danmoInformationCopy1 = new DanmoInformationCopy1();
            danmoInformationCopy1.setUserId(loginUser.getUserid());
            DanmoInformationCopy1 danmoInformationCopy11 = danmoInformationCopy1Mapper.selectDanmoInformation(danmoInformationCopy1);
            if (danmoInformationCopy11 == null) {
                return Result.error("请先上传个人信息");
            }
            danmoCollectShellfish.setInformationId(danmoInformationCopy11.getId());
            danmoCollectShellfish.setUserId(loginUser.getUserid());
            danmoCollectShellfish.setCreateTime(DateUtils.getNowDate());
            danmoCollectShellfish.setStatus(0);
            danmoCollectShellfishMapper.insertDanmoCollectShellfish(danmoCollectShellfish);

            Long id = danmoCollectShellfish.getId();
//            danmoCollectDoorListSetId(id, danmoCollectShellfish.getDanmoCollectDoorList());
            danmoCollectWorksListSetId(id, danmoCollectShellfish.getDanmoCollectWorksList());

//
//            danmoCollectDoorListAdd(danmoCollectShellfish.getDanmoCollectDoorList());
            danmoCollectWorksListAdd(danmoCollectShellfish.getDanmoCollectWorksList());
//            insertDanmoCollectDoor(danmoCollectShellfish);

        List<DanmoMarketPicture> pictureList = danmoCollectShellfish.getDanmoCollectWorksList().stream()
                .map(danmoCollectWorks -> {
                    DanmoMarketPicture danmoMarketPicture = new DanmoMarketPicture();
                    danmoMarketPicture.setName(danmoCollectWorks.getImageUrl());
                    return danmoMarketPicture;
                })
                .collect(Collectors.toList());


        DanmoMarketProducts build = DanmoMarketProducts.builder()
                .productName(danmoCollectShellfish.getTitle())
                .description(danmoCollectShellfish.getDescription())
                .views(0L)
                .userId(loginUser.getUserid())
                .informationId(danmoInformationCopy11.getId())
                .price(danmoCollectShellfish.getPrice())
                .danmoMarketPictureList(pictureList)
                .status(1)
                .build();

            //添加到书画市场
            danmoMarketProductsAdd.add(build);
            return Result.success(danmoCollectShellfish, "添加成功");
    }

        private String determineTable(Long associationType) {
            if (associationType == null) {
                return "danmo_information";
            }
            if (associationType == 1 || associationType == 7) {
                return "danmo_information_guo";
            }
            if (associationType == 2 || associationType == 8) {
                return "danmo_information_sheng";
            }
            if (associationType == 3 || associationType == 9) {
                return "danmo_information_shi";
            }
            if (associationType == 4 || associationType == 10) {
                return "danmo_information_gu";
            }
            if (associationType == 5 || associationType == 11) {
                return "danmo_information_she";
            }
            if (associationType == 6 || associationType == 12) {
                return "danmo_information_xing";
            } else {
                return "danmo_information_copy1";
            }
        }


    private Result  judgment(DanmoCollectShellfish danmoCollectShellfish){
        if (danmoCollectShellfish.getTitle()==null || danmoCollectShellfish.getTitle().equals("")){
            return Result.error("请输入标题");
        }

        if (danmoCollectShellfish.getDescription()==null|| danmoCollectShellfish.getDescription().equals("")){
            return Result.error("请输入作品介绍");
        }
        if (danmoCollectShellfish.getPrice()==null|| danmoCollectShellfish.getPrice().equals("")){
            return Result.error("请输入作品价格");
        }

        return null;
    }

    private void danmoCollectWorksListAdd(List<DanmoCollectWorks> danmoCollectWorksList) {

        danmoCollectShellfishMapper.danmoCollectWorksListAdd(danmoCollectWorksList);
    }

    private void danmoCollectDoorListAdd(List<DanmoCollectDoor> danmoCollectDoorList) {
        danmoCollectShellfishMapper.danmoCollectDoorListAdd(danmoCollectDoorList);
    }

    private void danmoCollectWorksListSetId(Long id, List<DanmoCollectWorks> danmoCollectWorksList) {
        for (DanmoCollectWorks danmoCollectWorks : danmoCollectWorksList) {
            danmoCollectWorks.setShellfishId(id);
        }
    }

    private void danmoCollectDoorListSetId(Long id, List<DanmoCollectDoor> danmoCollectDoorList) {

        for (DanmoCollectDoor danmoCollectDoor : danmoCollectDoorList) {
            danmoCollectDoor.setShellfishId(id);
        }
    }

    /**
     * 修改拾贝信息
     *
     * @param danmoCollectShellfish 拾贝信息
     * @return 结果
     */
    @Transactional
    @Override
    public Result updateDanmoCollectShellfish(DanmoCollectShellfish danmoCollectShellfish) {
        try {
            Result judgment = judgment(danmoCollectShellfish);
            if (judgment!=null){
                return judgment;
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return Result.notLoggedIn("请登录");
            }
            boolean b = danmoCollectMemberService.selectIsShow(loginUser.getUserid());
            if (b==false){
                return Result.error("请先开通");
            }
            danmoCollectShellfish.setUpdateTime(DateUtils.getNowDate());
            danmoCollectShellfishMapper.updateDanmoCollectShellfish(danmoCollectShellfish);

            danmoCollectShellfishMapper.deleteDanmoCollectWoorsByShellfishId(danmoCollectShellfish.getId());
            insetrDanmoCollectWoors(danmoCollectShellfish);
            return Result.success(danmoCollectShellfish, "修改成功");

        }catch (Exception e){
            return Result.error("修改失败");
        }

    }

    private void insetrDanmoCollectWoors(DanmoCollectShellfish danmoCollectShellfish) {
        List<DanmoCollectWorks> danmoCollectWorksList = danmoCollectShellfish.getDanmoCollectWorksList();
        Long id = danmoCollectShellfish.getId();
        if (StringUtils.isNotNull(danmoCollectWorksList)) {
            List<DanmoCollectWorks> list = new ArrayList<DanmoCollectWorks>();
            for (DanmoCollectWorks danmoCollectWorks : danmoCollectWorksList) {
                danmoCollectWorks.setShellfishId(id);
                list.add(danmoCollectWorks);
            }
            if (list.size() > 0) {
                danmoCollectShellfishMapper.insetrDanmoCollectWoors(list);
            }
        }
    }

    /**
     * 批量删除拾贝信息
     *
     * @param ids 需要删除的拾贝信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public Result deleteDanmoCollectShellfishByIds(Long[] ids) {
        danmoCollectShellfishMapper.deleteDanmoCollectDoorByShellfishIds(ids);
        danmoCollectShellfishMapper.deleteDanmoCollectWoorsByShellfishIds(ids);

        return Result.success(danmoCollectShellfishMapper.deleteDanmoCollectShellfishByIds(ids), "删除成功");
    }

    /**
     * 删除拾贝信息信息
     *
     * @param id 拾贝信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDanmoCollectShellfishById(Long id) {
        danmoCollectShellfishMapper.deleteDanmoCollectDoorByShellfishId(id);
        return danmoCollectShellfishMapper.deleteDanmoCollectShellfishById(id);
    }

    @Override
    public List<DanmoCollectShellfish> myShellfish(Long userId) {
        DanmoCollectShellfish danmoCollectShellfish = new DanmoCollectShellfish();
        danmoCollectShellfish.setUserId(userId);
        return danmoCollectShellfishMapper.selectDanmoCollectShellfishListMy(danmoCollectShellfish);
    }

    @Override
    public Result updateDanmoCollectShellfishById(Long id) {
        DanmoCollectShellfish danmoCollectShellfish = danmoCollectShellfishMapper.selectDanmoCollectShellfishById(id);
        if (danmoCollectShellfish.getStatus()==2) {
            return Result.error("商品已下架");
        }
        danmoCollectShellfish.setStatus(2);
        danmoCollectShellfishMapper.updateDanmoCollectShellfish(danmoCollectShellfish);
        return Result.success(id,"下架成功");
    }

    @Override
    public Result updateDanmoCollectShellfishListedById(Long id) {
//        DanmoCollectShellfish danmoCollectShellfish = danmoCollectShellfishMapper.selectDanmoCollectShellfishById(id);
        DanmoCollectShellfish danmoCollectShellfish = danmoCollectShellfishMapper.selectDanmoCollectShellfish(id);
        if (danmoCollectShellfish.getStatus()==0) {
            return Result.error("商品已上架");
        }
        danmoCollectShellfish.setStatus(0);
        danmoCollectShellfishMapper.updateDanmoCollectShellfish(danmoCollectShellfish);
        return Result.success(id,"上架成功");
    }


    @Autowired
    private DanmoCollectMaterialMapper danmoCollectMaterialMapper;

    /**
     * 查询拾贝信息收藏
     */
    @Override
    public Result selectDanmoCollectMaterialCollection() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 查询用户的收藏材料
        List<DanmoCollectMaterial> danmoCollectMaterials = danmoCollectMaterialMapper.selectDanmoCollectMaterialCollection(loginUser.getUserid());

        // 如果没有找到任何收藏材料，返回相应的错误信息
        if (danmoCollectMaterials == null || danmoCollectMaterials.isEmpty()) {
            return Result.error("暂无收藏");
        }

        // 假设您打算填充一个可变的列表来存放查询到的贝类
        List<DanmoCollectShellfish> danmoCollectShellfishs = new ArrayList<>();

        // 遍历所有收藏材料
        for (DanmoCollectMaterial danmoCollectMaterial : danmoCollectMaterials) {
            // 检查当前材料是否为 null
            if (danmoCollectMaterial == null) {
                return Result.error("查询失败：发现无效的收藏材料");
            }

            // 根据 shellfishId 查询拾贝信息
            DanmoCollectShellfish danmoCollectShellfish = danmoCollectShellfishMapper.selectDanmoCollectShellfishByIdAndUserId(danmoCollectMaterial.getShellfishId(),loginUser.getUserid());

            // 检查贝类信息是否为 null
            if (danmoCollectShellfish == null) {
                return Result.error("查询失败：未找到 ID 为 " + danmoCollectMaterial.getShellfishId() + " 的贝类");
            }

            // 添加到结果列表
            danmoCollectShellfishs.add(danmoCollectShellfish);
        }

        // 返回成功结果
        return Result.success(danmoCollectShellfishs);
    }

    @Autowired
    private DanmoPortfolioMapper danmoPortfolioMapper;
    @Override
    public DanmoCollectShellfish selectDanmoPortfolioById(Long id) {
        DanmoPortfolio danmoPortfolio = danmoPortfolioMapper.selectDanmoPortfolioById(id);
        DanmoCollectShellfish danmoCollectShellfish = new DanmoCollectShellfish();
        danmoCollectShellfish.setAuthor(danmoPortfolio.getAuthor());
        danmoCollectShellfish.setDescription(danmoPortfolio.getPictureIntroduction());
        danmoCollectShellfish.setTitle(danmoPortfolio.getName());
        danmoCollectShellfish.setPicture(danmoPortfolio.getPicture());
        danmoCollectShellfish.setInformationId(danmoPortfolio.getInformationId());

        return danmoCollectShellfish;
    }


    /**
     * 新增拾贝门头照信息
     *
     * @param danmoCollectShellfish 拾贝信息对象
     */
    public void insertDanmoCollectDoor(DanmoCollectShellfish danmoCollectShellfish) {
        List<DanmoCollectDoor> danmoCollectDoorList = danmoCollectShellfish.getDanmoCollectDoorList();
        Long id = danmoCollectShellfish.getId();
        if (StringUtils.isNotNull(danmoCollectDoorList)) {
            List<DanmoCollectDoor> list = new ArrayList<DanmoCollectDoor>();
            for (DanmoCollectDoor danmoCollectDoor : danmoCollectDoorList) {
                danmoCollectDoor.setShellfishId(id);
                list.add(danmoCollectDoor);
            }
            if (list.size() > 0) {
                danmoCollectShellfishMapper.batchDanmoCollectDoor(list);
            }
        }
    }
}
